package com.huiyan.hysys.service.impl;

import com.alibaba.fastjson.JSON;
import com.huiyan.hysys.bo.UserBo;
import com.huiyan.hysys.config.RedisKeyConfig;
import com.huiyan.hysys.config.SystemConfig;
import com.huiyan.hysys.dao.UserDao;
import com.huiyan.hysys.dao.UserLogDao;
import com.huiyan.hysys.entity.User;
import com.huiyan.hysys.entity.UserLog;
import com.huiyan.hysys.service.intf.UserService;
import com.huiyan.hysys.third.JedisUtil;
import com.huiyan.hysys.third.JwtUtil;
import com.huiyan.hysys.util.EncryptUtil;
import com.huiyan.hysys.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao dao;
    @Autowired
    private UserLogDao logDao;
    @Value("${idler.rsa.pri}")
    private String priKey;

    @Override
    public R checkPhone(String phone) {
        //1.
        User user=dao.selectByPhone(phone);
        //2.
        if(user!=null){
            //3.
            if(SystemConfig.USER_OK==user.getFlag()){
                return R.fail("亲，手机号已存在，请登陆！");
            }else {
                //4.
                return R.fail("亲，手机号异常，请联系客服！");
            }
        }else {
            return R.ok();
        }
    }

    @Override
    @Transactional//启用事务
    public R register(UserBo bo, String ip) {
        //1.校验-手机号可用性
        if(checkPhone(bo.getPhone()).getCode()== SystemConfig.R_OK){
            //2.校验-手机号注册验证码
            if(!JedisUtil.checkKey(RedisKeyConfig.CODE_R+bo.getPhone())){
                //3.密码进行脱敏
                User user=new User(SystemConfig.USER_OK, EncryptUtil.rsaEnc(priKey,bo.getPass()),bo.getPhone());
                //4.注册账号
                if(dao.insert(user)>0){
                    //5.新人有礼
                    logDao.insert(new UserLog(SystemConfig.USER_LOG_1,"注册新用户",ip,user.getId(),new Date()));

                    return R.ok();
                }
            }
        }
        return R.fail();
    }
    //唯一登陆
    @Override
    public R login(UserBo bo, String ip) {
        //令牌，前后端分离项目。调用接口的，可以是PC网站、手机网站、APP、小程序、智能硬件，不使用Session
        //1.查询数据库
        User user=dao.selectByPhone(bo.getPhone());
        //2.验证手机号是否正确
        if(user!=null && user.getFlag()== SystemConfig.USER_OK){
            //3.验证密码
            if(user.getPassword().equals(EncryptUtil.rsaEnc(priKey,bo.getPass()))){
                if(!JedisUtil.checkKey(RedisKeyConfig.USER_TOKEN_Phone+bo.getPhone())){
                    //4.登陆成功，生成令牌
                    String token= JwtUtil.createJwt(bo.getPhone());
                    //存储令牌
                    JedisUtil.addStr(RedisKeyConfig.USER_TOKEN_Phone+bo.getPhone(),token, RedisKeyConfig.USER_TOKEN_TIME);
                    JedisUtil.addStr(RedisKeyConfig.USER_TOKEN+token, JSON.toJSONString(user), RedisKeyConfig.USER_TOKEN_TIME);
                    //更新数据库
                    logDao.insert(new UserLog(SystemConfig.USER_LOG_2,"手机号登陆成功",ip,user.getId(),new Date()));
                    return R.ok(token);
                }else {
                    return R.fail("亲,你已在其他地方登陆！");
                }
            }
        }
        return R.fail("账号或密码的错误");
    }

    @Override
    public R loginCode(UserBo bo, String ip) {
        //短信验证码登陆
        User user=dao.selectByPhone(bo.getPhone());
        if(user!=null && user.getFlag()== SystemConfig.USER_OK){
            if(!JedisUtil.checkKey(RedisKeyConfig.USER_TOKEN_Phone+bo.getPhone())){
                if(JedisUtil.checkKey(RedisKeyConfig.CODE_L+bo.getPhone())) {
                    if (bo.getPass().equals(JedisUtil.getStr(RedisKeyConfig.CODE_L + bo.getPhone()))) {
                        //成功
                        //4.登陆成功，生成令牌
                        String token = JwtUtil.createJwt(bo.getPhone());
                        //存储令牌
                        JedisUtil.addStr(RedisKeyConfig.USER_TOKEN_Phone + bo.getPhone(), token, RedisKeyConfig.USER_TOKEN_TIME);
                        JedisUtil.addStr(RedisKeyConfig.USER_TOKEN + token, JSON.toJSONString(user), RedisKeyConfig.USER_TOKEN_TIME);
                        //更新数据库
                        logDao.insert(new UserLog(SystemConfig.USER_LOG_2, "短信验证码-登陆成功", ip, user.getId(), new Date()));
                        return R.ok(token);

                    }
                }
            }else {
                return R.fail("亲,你已在其他地方登陆！");
            }
        }
        return R.fail("账号或验证码错误");
    }

    @Override
    public R loginOut(String token, String ip) {
        String key= RedisKeyConfig.USER_TOKEN+token;
        if(JedisUtil.checkKey(key)){
            User user=JSON.parseObject(JedisUtil.getStr(key), User.class);
            JedisUtil.delKey(RedisKeyConfig.USER_TOKEN_Phone+user.getPhone());
            JedisUtil.delKey(key);
            logDao.insert(new UserLog(SystemConfig.USER_LOG_3,"退出了登陆",ip,user.getId(),new Date()));
            return R.ok();
        }
        return R.fail();
    }

    @Override
    public R checkToken(String token) {
        if(JedisUtil.checkKey(RedisKeyConfig.USER_TOKEN+token)){
            return R.ok();
        }
        return R.fail();
    }

    @Override
    public R getToken(String token) {
        String key= RedisKeyConfig.USER_TOKEN+token;
        if(JedisUtil.checkKey(key)){
            String json= JedisUtil.getStr(key);
            User user=JSON.parseObject(json, User.class);
            user.setPassword("");
            return R.ok(user);
        }
        return R.fail();
    }
}
